﻿using Ekton_Manage_Framework.Redis;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace Ekton_Manage_Framework.Methods
{
    public class HttpGetUser
    {
        private readonly IHttpContextAccessor _accessor;
        private readonly Connection _connection;

        public HttpGetUser(IHttpContextAccessor accessor,
            Connection connection)
        {
            _accessor = accessor;
            _connection = connection;
        }
        public async Task<string> GetToken()
        {
            return _accessor.HttpContext.Request.Headers["authorization"].ToString().Replace("Bearer", string.Empty).Trim();
        }

        public async Task<string> GetUserInfoFromToken()
        {
            return _connection.db.StringGet(await GetToken());
        }

        public List<string> AllowApi = new List<string>() { "/api/Home/GetToken", "/api/ApiLogin/GetToken", "/api/Common/GetCompany", "/api/Common/SendEmail", "/api/ApiLogin/ApiPostUserPass", "/api/Home/PostUserPwd", "/api/ApiLogin/ApiPostUserRegsiter", "/api/Sys/GetCopyRight", "/api/Sys/PutCopyRight", "/api/ApiAgreement/GetAllNewsList", "/api/ApiAgreement/PutAgreementList" };

        public async Task<object> GetUser()
        {
            if (_accessor.HttpContext == null) return default(object);
            if (!AllowApi.Contains(_accessor.HttpContext.Request.Path))
            {
                try
                {
                    string claimInfo = _accessor.HttpContext.AuthenticateAsync().Result.Principal.Claims.FirstOrDefault(t => t.Type.Equals(ClaimTypes.NameIdentifier))?.Value;
                    var userInfo = JsonConvert.DeserializeObject(claimInfo);
                    return userInfo;
                }
                catch
                {

                }
            }
            return default(object);
        }

        public async Task<string> GetClientIP()
        {
            return this._accessor.HttpContext.Connection.RemoteIpAddress.ToString().Replace(":", string.Empty).Replace("f", string.Empty);
        }
    }
}
